查看原文
其他

ASP.NET Core 如何返回 File

DotNet 2022-07-19

The following article is from NET技术问答 Author StackOverflow

咨询区


想在 ASP.Net Web API 中返回 File 文件,我目前的做法是将 Action 返回值设为 HttpResponseMessage,参考代码如下:

public async Task<HttpResponseMessage> DownloadAsync(string id)  
{  
    var response = new HttpResponseMessage(HttpStatusCode.OK);  
    response.Content = new StreamContent({{__insert_stream_here__}});  
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");  
    return response;  
}  

当我在浏览器测试时,我发现Api将 HttpResponseMessage 作为 json格式返回,同时 Http Header 头为 application/json,请问我该如何正确配置成文件流返回。

回答区

我觉得大概有两种做法:

1、返回 FileStreamResult

[HttpGet("get-file-stream/{id}"]  
public async Task<FileStreamResult> DownloadAsync(string id)  
{  
      var fileName="myfileName.txt";  
      var mimeType="application/....";   
      Stream stream = await GetFileStreamById(id);  
  
      return new FileStreamResult(stream, mimeType)  
        {  
            FileDownloadName = fileName  
        };  
    }  

2、返回 FileContentResult

    [HttpGet("get-file-content/{id}"]  
    public async Task<FileContentResult> DownloadAsync(string id)  
    {  
        var fileName="myfileName.txt";  
        var mimeType="application/....";   
        byte[] fileBytes = await GetFileBytesById(id);  
  
        return new FileContentResult(fileBytes, mimeType)  
        {  
            FileDownloadName = fileName  
        };  
    }  

这是因为你的代码将 HttpResponseMessage 视为一个 Model,如果你的代码是 Asp.NET Core 的话,其实你可以混入一些其他特性,比如将你的 Action 返回值设置为一个派生自 IActionResult 下的某一个子类,参考如下代码:

[Route("api/[controller]")]  
public class DownloadController : Controller {  
    //GET api/download/12345abc  
    [HttpGet("{id}")]  
    public async Task<IActionResult> Download(string id) {  
        Stream stream = await {{__get_stream_based_on_id_here__}}  
  
        if(stream == null)  
            return NotFound(); // returns a NotFoundResult with Status404NotFound response.  
  
        return File(stream, "application/octet-stream"); // returns a FileStreamResult  
    }      
}  

点评区

记得我在 webapi 中实现类似功能时,我用的就是后面这位大佬提供的方式, ActionResult + File 的方式,简单粗暴。


- EOF -

推荐阅读  点击标题可跳转
C#为什么你应该更喜欢 is 关键字而不是 == 运算符.NET 某机械臂智能机器人控制系统MRS CPU爆高分析 .NET 6 数组拷贝性能对比


看完本文有收获?请转发分享给更多人

推荐关注「DotNet」,提升.Net技能 

点赞和在看就是最大的支持❤️

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存